package ru.spb.osll.myfit.server.templateloader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.server.handler.PageLoader;
import ru.spb.osll.myfit.server.parser.PageUtils;
import ru.spb.osll.myfit.util.CollectionUtils;
import ru.spb.osll.myfit.wikiverifier.iterator.FileSystemIteratorListener;
import util.GracefulNamer;

public class TemplateLoaderFSIteratorListener implements
    FileSystemIteratorListener {
  private PageLoader m_loader;
  private HashMap<String, Vector<String>> m_templates;

  // FIXME
  public TemplateLoaderFSIteratorListener() {
    m_loader = new PageLoader();
    m_templates = new HashMap<String, Vector<String>>();
  }

  public HashMap<String, Vector<String>> getTemplates() {
    return m_templates;
  }

  @Override
  public void listen(String filename) {
    try {
      Page page = m_loader.loadPage(filename);
      for (PageElement elem : page.getElements()) {
        if (elem instanceof Table) {
          Table table = (Table) elem;
          if (table.getData().size() != 0) {
            Vector<String> rawTable = new Vector<String>(
                CollectionUtils
                    .list(PageUtils.tableToString(table).split("\n")));
            m_templates.put(getClassName(table.getData().get(0)), rawTable);
          }
        }
      }
    } catch (IOException e) {
    }
  }

  @Override
  public void handleFinish() {
  }

  private String getClassName(Vector<TableCell> tableLine) {
    return GracefulNamer.disgrace(tableLine.get(0).getText());
  }
}
